<template>
  <div class="base">
    <common-form :form="form" ref="form" class="form" :formData="formDataArr" :rules="rules">
      <!--提示-->
      <div slot="ctime" class="prompt">
        {{ $t('configLazyLoad.businessConfig.stepTimeTip') }}{{ flowTime.show
        }}{{ $t('configLazyLoad.businessConfig.stepTimeTip1') }}
      </div>
      <div slot="notifyUser" class="prompt">
        {{ $t('configLazyLoad.businessConfig.stepTimeTip2') }}
      </div>
      <div slot="assignStrategy" class="prompt">
        <span v-if="form.assignStrategy === 2">{{ $t('configLazyLoad.businessConfig.stepTimeTip5') }}</span>
        <span v-else-if="form.assignStrategy === 1">{{ $t('configLazyLoad.businessConfig.stepTimeTip6') }}</span>
        <span v-else-if="form.assignStrategy === 0">{{ $t('configLazyLoad.businessConfig.stepTimeTip7') }}</span>
        <span v-else></span>
      </div>
      <el-button class="primary_btn" type="primary" size="mini" slot="button" @click.stop="update">{{
        $t('public.save')
      }}</el-button>
    </common-form>
  </div>
</template>
<script>
import commonForm from '../base/commonForm'
import { deepClone } from '@/utils/m7Utils'
import { getRoleAgents, getQueueAgents, parseIntTime, timeTrans } from '@/utils/workflowUtils'
import { checkform } from '@/utils/validate'
const baseForm = {
  name: '',
  ctype: true,
  ctime: '',
  isBegin: '',
  notifyUser: [],
  defaultAgent: '',
  assignStrategy: '',
  _id: '',
  flow_id: '',
  referOrderInitStatus: false
}
export default {
  name: 'base-info',
  props: {
    currentStepInfo: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    let self = this
    let validate1 = (rule, value, callback) => {
      if (checkform(value, 'Number5')) {
        callback(new Error(this.$t('configLazyLoad.businessConfig.mustBePositiveInteger')))
      } else if (self.flowTime.seconds < parseIntTime(self.form.ctype, self.form.ctime)) {
        callback(new Error(this.$t('configLazyLoad.businessConfig.mustBeLessThanOrEqual') + self.flowTime.show))
      } else {
        callback()
      }
    }
    return {
      form: deepClone(baseForm),
      formData: [
        { label: this.$t('config.business.stepName'), name: 'name', type: 'input' },
        { label: this.$t('configLazyLoad.businessConfig.timeLimit'), name: 'ctime', type: 'timeOut', time: 'ctype' },
        { label: this.$t('config.business.notifyUser'), name: 'notifyUser', type: 'select', multiple: true, data: [] },
        {
          label: this.$t('configLazyLoad.businessConfig.allocationPolicy'),
          name: 'assignStrategy',
          type: 'doubleSelect',
          data: [
            { label: this.$t('public.noResult'), value: '' },
            { label: this.$t('callServiceSkillGroup.callServiceSkillGroup22'), value: 2 },
            { label: this.$t('callServiceSkillGroup.callServiceSkillGroup23'), value: 1 },
            { label: this.$t('configLazyLoad.businessConfig.defaulHandler'), value: 0 }
          ],
          referOrderInitStatus: 'referOrderInitStatus',
          data1: [],
        }
      ],
      rules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value.length > 10) {
                callback(new Error(this.$t('configLazyLoad.businessConfig.nameTip')))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        ctime: [{ required: false, validator: validate1, trigger: 'blur' }]
      }
    }
  },
  inject: ['busType'],
  computed: {
    formDataArr() {
      return this.formData.filter((item) => {
        if (item.name === 'assignStrategy' && (this.currentStepInfo.type === 'sys' || this.currentStepInfo.isBegin)) {
          return false
        }
        return true
      })
    },
    flowTime() {
      let flowInfo = this.$store.state.config.businessConfig[this.busType].flowInfo || {}
      let obj = { show: '', seconds: Infinity }
      if (flowInfo.ctype && flowInfo.ctime) {
        obj.show = timeTrans(flowInfo.ctype, flowInfo.ctime)
        obj.seconds = parseIntTime(flowInfo.ctype, flowInfo.ctime)
      }
      return obj
    }
  },
  components: {
    commonForm
  },
  methods: {
    // 回显
    initData() {
      this.defaultAgent()
      this.$refs.form.clearValidate()
      for (let i in this.form) {
        if (i === 'notifyUser') {
          this.form[i] = deepClone(this.currentStepInfo[i]) || []
        } else {
          this.form[i] = this.currentStepInfo[i]
        }
      }
      if (!this.form.ctype) {
        this.form.ctype = 'min'
      }
      if (!this.form.referOrderInitStatus || this.form.referOrderInitStatus === 'close') {
        this.form.referOrderInitStatus = false
      } else {
        this.form.referOrderInitStatus = true
      }
      if (!this.form.assignStrategy) {
        // 兼容旧数据
        if (this.form.defaultAgent) {
          this.form.assignStrategy = 0
        } else {
          this.form.assignStrategy = ''
        }
      }
    },
    // 生成默认处理人
    async defaultAgent() {
      let actions = this.currentStepInfo.actions || []
      let roles = []
      let queues = []
      for (let i = 0; i < actions.length; i++) {
        let actionsItem = actions[i]
        // 判断角色还是技能组
        if (actionsItem.actionAllow === 1) {
          if (actionsItem.actionQueue.length > 0) {
            // 技能组
            actionsItem.actionQueue.forEach((item) => {
              queues.push(item)
            })
          }
        } else {
          //兼容老数据，之前是字符串
          if (!Array.isArray(actionsItem.actionRole)) {
            actionsItem.actionRole = [actionsItem.actionRole]
          }
          // 角色
          if (actionsItem.actionRole.length > 0) {
            actionsItem.actionRole.forEach((item) => {
              roles.push(item)
            })
          }
        }
      }
      // 多个步骤动作，会存在角色和技能组同时存在的情况
      let queueAgentList = []
      let roleAgentList = []
      if (roles.length > 0) {
        roleAgentList = getRoleAgents(roles, false, 'busConfig') || []
      }
      if (queues.length > 0) {
        // 获取工单技能组
        queueAgentList = await getQueueAgents(queues, false)
      }
      let agents = [...new Set(roleAgentList.concat(queueAgentList))]
      let data = agents.map((item) => {
        let label = item.displayName
        // ‘工单创建人’没有exten
        if (item.exten) {
          label += `[${item.exten}]`
        }
        return { label, value: item._id, status: item.status }
      })
      data.unshift({ label: this.$t('public.noResult'), value: '' })
      this.formData.forEach((item) => {
        if (item.name === 'assignStrategy') {
          item.data1 = data
        }
      })
    },
    reset() {
      this.$refs.form.reset()
    },
    // 更新步骤信息
    update() {
      let data = this.$refs.form.submit()
      console.log(data, 'data')
      if (data.success) {
        let form = deepClone(data.data)
        form.referOrderInitStatus ? (form.referOrderInitStatus = 'open') : (form.referOrderInitStatus = 'close')
        // 当分配策略为默认处理人时，未选择默认处理人，给出提示
        if (form.assignStrategy === 0 && !form.defaultAgent) {
          this.$message.warning(this.$t('configLazyLoad.businessConfig.stepTimeTip4'))
        } else {
          if (form.assignStrategy !== 0) {
            form.defaultAgent = ''
          }
          form.notifyUser = form.notifyUser.join(',')
          this.$store.dispatch('updateBusinessStepInfo', form).then((res) => {
            if (res.success) {
              this.$message.success(this.$t('monitor.saveSuccess'))
              this.$store.commit('flowConfig/UPDATE_STEP_INFO', data.data)
            }
          })
        }
      }
    }
  },
  beforeMount() {
    this.$store.dispatch('getCache', { type: 'agents' }).then((res) => {
      let agent = res || []
      let data = agent.map((item) => {
        return { label: `${item.displayName}[${item.exten}]`, value: item._id, status: item.status }
      })
      console.log(data)
      data.unshift({ label: this.$t('configLazyLoad.businessConfig.currentHandlerSuperior'), value: 'masterLeader' })
      this.formData.forEach((item) => {
        if (item.name === 'notifyUser') {
          item.data = data
        }
      })
      console.error(this.formData)
    })
  }
}
</script>

<style scoped lang="stylus">
@import '../../../../../assets/common.styl'
.base
  padding 20px 0
  box-sizing border-box
.form
  width: 340px
  margin-right 20px
.prompt
  color $c-prompt
  font-size 12px
  line-height 16px
  padding-top 3px
.button-wrap
  text-align center
</style>
